package com.xquant.trade.risk.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.xquant.common.security.annotation.RequiresPermissions;
import com.xquant.common.security.utils.SecurityUtils;
import com.xquant.trade.risk.entity.VGroup;
import com.xquant.trade.risk.service.GroupService;
import com.xquant.trade.utils.CommResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("group")
public class GroupController {

    @Autowired
    private GroupService groupService;

    /**
     * 查询 虚拟组合
     */
    @RequiresPermissions("risk:profitmanage:profitinfo:list")
    @RequestMapping(value = "getVGroupList.action")
    public PageInfo getVGroupList(@RequestParam Map<String, Object> param) {
        param.put("userId",SecurityUtils.getUserId());
        PageInfo<List<VGroup>> pageInfo = groupService.getVGroupList(param);
        return pageInfo;
    }

    /**
     * 查询 虚拟组合
     */
    @RequiresPermissions("risk:profitmanage:profitinfo:list")
    @RequestMapping(value = "queryVGroupCombox.action")
    public List queryVGroupCombox(@RequestParam Map<String, Object> param) {
        param.put("userId",SecurityUtils.getUserId());
        List list = groupService.queryVGroupCombox(param);
        return list;
    }

    @RequestMapping(value = "queryGroupUserAndDeptPerm.action")
    public List queryGroupUserAndDeptPerm(@RequestParam Map<String,Object> param){
        List list = groupService.getGroupUserAndDeptPerm(param);
        return list;
    }

    /**
     * 新增组合
     */
    @RequiresPermissions("risk:profitmanage:profitinfo:add")
    @RequestMapping(value = "/addVGroup.action")
    public CommResponse addVGroup(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        VGroup vGroup = new VGroup();
        vGroup.setGroupCode((String) param.get("groupCode"));
        vGroup.setGroupName((String) param.get("groupName"));

        boolean check = groupService.checkGroupName(vGroup);
        boolean check2 = groupService.checkGroupCode(vGroup);
        if(check&&check2){
            String groupId = groupService.getGroupId(param);
            param.put("groupId", groupId);
            ArrayList<String> userPerms = new ArrayList<>();
            ArrayList<String> deptPerms = new ArrayList<>();
            String allocateDeptAndUsers = param.get("allocateDeptAndUser").toString();

            //创建人所属部门
            String createDeptId=SecurityUtils.getLoginUser().getSysUser().getDeptId().toString();

            //将创建人所属部门的上级部门加入deptPerms
            String deptAncestorIds = groupService.getDeptAncestors(createDeptId);
            List<String> deptAncestorIdArrs= Arrays.asList(deptAncestorIds.split(","));
            for(String deptAncestorArr : deptAncestorIdArrs){
                if("0".equals(deptAncestorArr) != true){
                    deptPerms.add(deptAncestorArr);
                }
            }

            for(String allocateDeptAndUser:allocateDeptAndUsers.split(",")){
                if(allocateDeptAndUser.charAt(0) == 'u'){
                    userPerms.add(allocateDeptAndUser.substring(2));
                }else if(allocateDeptAndUser.charAt(0) == 'd'){
                    deptPerms.add(allocateDeptAndUser.substring(2));
                }
            }
            if(userPerms.size() > 0){
                param.put("userIds",userPerms);
            }
            if(deptPerms.size() > 0){
                param.put("deptIds",deptPerms);
            }
            groupService.addVGroup(param);
            return new CommResponse(true, "保存成功");
        }else if(!check){
            return CommResponse.failure("组合名称重复");
        }else {
            return CommResponse.failure("组合编号重复");
        }


    }

    @RequiresPermissions("risk:profitmanage:profitinfo:allocate")
    @RequestMapping(value = "/updateGroupPerm.action")
    public CommResponse updateGroupPerm(@RequestParam Map<String,Object> param) {
        ArrayList<String> userPerms = new ArrayList<>();
        ArrayList<String> deptPerms = new ArrayList<>();
        String allocateDeptAndUsers = param.get("allocateDeptAndUser").toString();
        //创建人所属部门
        String createDeptId=SecurityUtils.getLoginUser().getSysUser().getDeptId().toString();

        //将创建人所属部门的上级部门加入deptPerms
        String deptAncestorIds = groupService.getDeptAncestors(createDeptId);
        List<String> deptAncestorIdArrs= Arrays.asList(deptAncestorIds.split(","));
        for(String deptAncestorArr : deptAncestorIdArrs){
            if("0".equals(deptAncestorArr) != true){
                deptPerms.add(deptAncestorArr);
            }
        }
        for(String allocateDeptAndUser:allocateDeptAndUsers.split(",")){
            if(allocateDeptAndUser.charAt(0) == 'u'){
                userPerms.add(allocateDeptAndUser.substring(2));
            }else if(allocateDeptAndUser.charAt(0) == 'd'){
                deptPerms.add(allocateDeptAndUser.substring(2));
            }
        }
        if(userPerms.size() > 0){
            param.put("userIds",userPerms);
        }
        if(deptPerms.size() > 0){
            param.put("deptIds",deptPerms);
        }
        groupService.updateGroupPerm(param);
        return new CommResponse(true,"操作成功");

    }

    /**
     * 修改组合
     */
    @RequiresPermissions("risk:profitmanage:profitinfo:edt")
    @RequestMapping(value = "/updateVGroup.action")
    public CommResponse updateVGroup(@RequestParam Map<String, Object> param) {

        VGroup vGroup = new VGroup();
        vGroup.setGroupCode((String) param.get("groupCode"));
        vGroup.setGroupName((String) param.get("groupName"));
        boolean check = groupService.checkGroupName(vGroup);

        if(check){
            param.put("userId", SecurityUtils.getUserId());
            param.put("groupSchema", param.get("groupSchema").toString());
            groupService.updateVGroup(param);
            return new CommResponse(true, "操作成功");
        }else {
            return CommResponse.failure("组合名称重复");
        }

    }

    /**
     * 删除组合
     */
    @RequiresPermissions("risk:profitmanage:profitinfo:del")
    @RequestMapping(value = "/deleteVGroup.action")
    public CommResponse deleteVGroup(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        groupService.deleteVGroup(param);
        return new CommResponse(true, "操作成功");
    }

    /**
     * 移入 组合
     */
    @RequestMapping(value = "/upGroupBalance.action")
    @PreAuthorize("@ss.hasPermi('risk:profitmanage:tradeprofit:add')")
    public CommResponse upGroupBalance(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        JSONArray jsonArray = JSONUtil.parseArray(param.get("data"));
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
            Map map = (Map) jsonObject;
            param.putAll(map);
            groupService.upGroupBalance(param);
        }
        return new CommResponse(true, "操作成功");
    }

    /**
     * 移出 组合
     */
    @RequestMapping(value = "/downGroupBalance.action")
    @PreAuthorize("@ss.hasPermi('risk:profitmanage:tradeprofit:edt')")
    public CommResponse downGroupBalance(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        JSONArray jsonArray = JSONUtil.parseArray(param.get("data"));
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(i));
            Map map = (Map) jsonObject;
            param.putAll(map);
            groupService.downGroupBalance(param);
        }
        return new CommResponse(true, "操作成功");
    }

    /**
     * 组合 任务执行
     */
    @RequestMapping(value = "/handleGroupBalance.action")
    @PreAuthorize("@ss.hasPermi('risk:profitmanage:profitinfo:exec')")
    public CommResponse handleGroupBalance(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        groupService.handleGroupBalance(param);
        return new CommResponse(true, "操作成功");
    }

}
